package com.hrm.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hrm.config.JSPPage;
import com.hrm.config.MsgType;
import com.hrm.entity.Message;
import com.hrm.entity.Role;
import com.hrm.entity.User;
import com.hrm.service.UserLogService;
import com.hrm.service.UserService;
import com.hrm.util.DateUtil;
import com.hrm.util.JSONUtil;
import com.hrm.util.Page;


@Controller
@RequestMapping("/user.do")
public class UserAction {
	private static final Log log = LogFactory.getLog(UserAction.class); 
	@Autowired
	private UserService userService;
	@Autowired
	private UserLogService userLogService;
	public UserLogService getUserLogService() {
		return userLogService;
	}
	public void setUserLogService(UserLogService userLogService) {
		this.userLogService = userLogService;
	}
	public UserService getUserService() {
		return userService;
	}
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	@RequestMapping(params = "method=getUsers")
	public String getUsers(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		//获取所有数据的前15条数据
		Page page = new Page();
		page.setPagesize(Integer.parseInt(request.getParameter("rows")));
		page.setCurrentpage(Integer.parseInt(request.getParameter("page")));
		Map<String, Object> searchMap = new HashMap<String, Object>();
		if("true".equals(request.getParameter("_search"))){
			searchMap.put(request.getParameter("searchField"),request.getParameter("searchString"));
		}
		List<User> users = userService.getUsers(page);
		page.setCounts(userService.getUserCounts());
		if(users!=null){
			log.info("begin to getUsers");
			try {
				Map<String, Object> resultMap2 = new HashMap<String, Object>();
				resultMap2.put("page", page.getCurrentpage()+"");
				log.debug("currentpage="+page.getCurrentpage());
				log.debug("countpage="+page.getCountPage());
				log.debug("records="+page.getCounts());
				resultMap2.put("total", page.getCountPage()+"");
				resultMap2.put("records", page.getCounts()+"");
				List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
				for(User u:users){
					Map<String, Object> rowMap =new HashMap<String, Object>();
					rowMap.put("id", u.getId());
					List<String> list = new ArrayList<String>();
					list.add(u.getId()+"");
					list.add(u.getUserName()+"");
					//list.add(u.getPassword()+"");
					list.add(u.getRId()+"");
					list.add(u.getCreateUserName()+"");
					list.add(DateUtil.formate(u.getCreateDate())+"");
					List<Role> roles=new ArrayList<Role>();
					roles=userService.getRolesByUserId(u.getId());
					StringBuffer stringBuffer = new StringBuffer();
					for(int i=0;i<roles.size();i++){
						if(i!=roles.size()-1){
							stringBuffer.append(roles.get(i).getRoleName()+",");
						}else{
							stringBuffer.append(roles.get(i).getRoleName());
						}
					}
					list.add(stringBuffer.toString());
					rowMap.put("cell", list);
					rows.add(rowMap);
				}
				resultMap2.put("rows", rows);
				String result=JSONUtil.parseMap(resultMap2);
				response.getWriter().print(result);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			try {
				Message message = new Message("ERROR", "获取数据失败或数据为空!", new Date());
				System.out.println(message.toJSONString());
				response.getWriter().print(message.toJSONString());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=getUsersByName")
	public String getUsersByName(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		String username=request.getParameter("name")==null?"":request.getParameter("name");
		log.debug("name================"+username);
		//获取所有数据的前15条数据
		Page page = new Page();
		page.setPagesize(Integer.parseInt(request.getParameter("rows")));
		page.setCurrentpage(Integer.parseInt(request.getParameter("page")));
		Map<String, Object> searchMap = new HashMap<String, Object>();
		if("true".equals(request.getParameter("_search"))){
			searchMap.put(request.getParameter("searchField"),request.getParameter("searchString"));
		}
		List<User> users = userService.getUsersByName(username,page);
		page.setCounts(userService.getUserByNameCounts(username));
		if(users!=null){
			log.info("begin to getUsersByName");
			try {
				Map<String, Object> resultMap2 = new HashMap<String, Object>();
				resultMap2.put("page", page.getCurrentpage()+"");
				log.error("currentpage="+page.getCurrentpage());
				log.error("countpage="+page.getCountPage());
				log.error("records="+page.getCounts());
				resultMap2.put("total", page.getCountPage()+"");
				resultMap2.put("records", page.getCounts()+"");
				List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
				for(User u:users){
					Map<String, Object> rowMap =new HashMap<String, Object>();
					rowMap.put("id", u.getId());
					List<String> list = new ArrayList<String>();
					list.add(u.getId()+"");
					list.add(u.getUserName()+"");
					//list.add(u.getPassword()+"");
					list.add(u.getRId()+"");
					list.add(u.getCreateUserName()+"");
					list.add(DateUtil.formate(u.getCreateDate())+"");
					List<Role> roles=new ArrayList<Role>();
					roles=userService.getRolesByUserId(u.getId());
					StringBuffer stringBuffer = new StringBuffer();
					for(int i=0;i<roles.size();i++){
						if(i!=roles.size()-1){
							stringBuffer.append(roles.get(i).getRoleName()+",");
						}else{
							stringBuffer.append(roles.get(i).getRoleName());
						}
					}
					list.add(stringBuffer.toString());
					rowMap.put("cell", list);
					rows.add(rowMap);
				}
				resultMap2.put("rows", rows);
				String result=JSONUtil.parseMap(resultMap2);
				response.getWriter().print(result);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			try {
				Message message = new Message("ERROR", "获取数据失败或数据为空!", new Date());
				response.getWriter().print(message.toJSONString());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=addUser")
	public String addUser(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		Message message = new Message();
		String userName=request.getParameter("userName")==null?"":request.getParameter("userName");
		String password=request.getParameter("password")==null?"":request.getParameter("password");
		String confirmPassword=request.getParameter("confirmPassword")==null?"":request.getParameter("confirmPassword");
		String roleids=request.getParameter("roleids")==null?"":request.getParameter("roleids");
		if("".equals(userName)||userName.getBytes().length>=20){
			message.setMsg("用户名不能为空且长度必须在20个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if("".equals(password)||password.getBytes().length>=20||!password.equals(confirmPassword)){
			message.setMsg("密码不能为空且长度必须在20个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String[] tmp=roleids.split(",");
		for(String s:tmp){
			try {
				Integer.parseInt(s);
			} catch (Exception e) {
				message.setMsg("角色ID必须为数字!");
				message.setStatus("ERROR");
				message.setTimestamp(new Date());
				try {
					response.getWriter().print(message.toJSONString());
					return null;
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		if("".equals(roleids)){
			message.setMsg("请至少选择一个角色!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(!password.equals(confirmPassword)){
			message.setMsg("重复密码必须与密码字段一致!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		User user = new User();
		user.setUserName(userName);
		user.setPassword(password);
		user.setCreateDate(new Date());
		User sessionUser = (User) request.getSession().getAttribute("user");
		user.setCreateUserId(sessionUser.getId());
		user.setCreateUserName(sessionUser.getUserName());
		if(userService.addUser(user,tmp)<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("新增用户成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			ActionUtil.insertLog(request, MsgType.TYPE_USER, "新增用户:"+user.getUserName(),userLogService);
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=updateUser")
	public String updateUser(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id"));
		User user = userService.getUserById(id);
		if(user==null){
			Message message = new Message();
			message.setMsg("获取用户信息失败!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		map.put("user", user);
		return JSPPage.USER_EDIT;
	}
	@RequestMapping(params = "method=updateUserById")
	public String updateUserById(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id")==null?"-1":request.getParameter("id"));
		if(id==-1){
			Message message = new Message();
			message.setMsg("必须传入用户ID才能编辑!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String userName=request.getParameter("userName")==null?"":request.getParameter("userName");
		if("".equals(userName)||userName.getBytes().length>=20){
			Message message = new Message();
			message.setMsg("用户名不能为空且长度必须在20个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String roleids=request.getParameter("roleids")==null?"":request.getParameter("roleids");
		if("".equals(roleids)){
			Message message = new Message();
			message.setMsg("用户必须至少有一个所属角色!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		User user = new User();
		user.setId((int) id);
		user.setUserName(userName);
		Message message = new Message();
		if(userService.updateUser(user,roleids.split(","))<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("编辑用户成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			ActionUtil.insertLog(request, MsgType.TYPE_USER, "编辑用户:"+user.getUserName(),userLogService);
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=deleteUserById")
	public String deleteUserById(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		String userids = request.getParameter("userids")==null?"":request.getParameter("userids");
		Message message = new Message();
		if("".equals(userids)){
			message.setMsg("必须传入用户ID才能删除!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(userService.deleteUserById(userids)<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("删除用户成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			ActionUtil.insertLog(request, MsgType.TYPE_USER, "删除用户:用户id为"+userids,userLogService);
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=resetPwdToDefault")
	public String resetPwdToDefault(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		String userids = request.getParameter("userids")==null?"":request.getParameter("userids");
		Message message = new Message();
		if("".equals(userids)){
			message.setMsg("必须传入用户ID才能删除!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(userService.resetPwdToDefault(userids)<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("重置用户密码成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			ActionUtil.insertLog(request, MsgType.TYPE_USER, "重置用户密码:用户id为"+userids,userLogService);
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
}
